import { VisualizationEvent } from "../components/FeatureProcessor";

export class BigStarLayer {
  private canvas: HTMLCanvasElement;
  private ctx: CanvasRenderingContext2D;
  private isPlaying: boolean = false;
  private animationFrameId: number | null = null;
  private baseSize: number = 80; // 基础大小改为80像素
  private glowIntensity: number = 0; // 光晕强度

  constructor(canvas: HTMLCanvasElement) {
    this.canvas = canvas;
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      throw new Error('Unable to get 2D context');
    }
    this.ctx = ctx;
  }

  public update(event: VisualizationEvent): void {
    if (!this.isPlaying) return;

    // 根据RMS能量计算光晕强度，使用0.1作为归一化因子
    this.glowIntensity = Math.min(1, event.rms / 0.1);
    
    // 绘制五角星和光晕
    this.draw();
  }

  private draw(): void {
    const centerX = this.canvas.width / 2;
    const centerY = this.canvas.height / 2;
    
    // 绘制多层金色光晕，增强光晕的真实感
    if (this.glowIntensity > 0) {
      // 绘制多层光晕，创建更柔和的发光效果
      for (let i = 0; i < 3; i++) {
        const layerIntensity = Math.pow(this.glowIntensity, 0.4 + i * 0.3); // 不同层级使用不同的强度
        const glowSize = this.baseSize * (1 + layerIntensity * (2.0 - i * 0.5)); // 每层光晕大小不同
        
        this.ctx.save();
        
        // 创建放射状渐变实现更真实的光晕效果
        const gradient = this.ctx.createRadialGradient(
          centerX, centerY, this.baseSize * 0.3,     // 内圆（从五角星内部开始）
          centerX, centerY, glowSize                 // 外圆（扩展到光晕边缘）
        );
        
        // 设置渐变颜色，创建更真实的光晕效果
        const alpha = 0.3 * layerIntensity * (1 - i * 0.25); // 每层透明度递减
        gradient.addColorStop(0, `rgba(255, 255, 200, ${alpha * 0.8})`);     // 内部：淡黄色
        gradient.addColorStop(0.4, `rgba(255, 220, 100, ${alpha * 0.5})`);   // 中间：金黄色
        gradient.addColorStop(0.7, `rgba(255, 180, 50, ${alpha * 0.3})`);    // 外部：深金色
        gradient.addColorStop(1, `rgba(200, 100, 0, 0)`);                    // 最外层：透明
        
        this.ctx.fillStyle = gradient;
        this.ctx.globalCompositeOperation = 'lighter'; // 使用lighter混合模式增强发光效果
        
        // 绘制光晕（较大的五角星）
        this.drawStar(centerX, centerY, 5, glowSize, glowSize * 0.4);
        this.ctx.fill();
        this.ctx.restore();
      }
    }
    
    // 绘制固定的红色五角星（不随音乐变化）
    this.ctx.save();
    this.ctx.fillStyle = 'red';
    this.ctx.strokeStyle = 'red';
    this.ctx.lineWidth = 2;
    this.ctx.globalAlpha = 1; // 确保不透明度为1
    this.drawStar(centerX, centerY, 5, this.baseSize, this.baseSize * 0.4);
    this.ctx.fill();
    this.ctx.stroke();
    this.ctx.restore();
  }

  // 绘制五角星的辅助函数
  private drawStar(
    cx: number, 
    cy: number, 
    spikes: number, 
    outerRadius: number, 
    innerRadius: number
  ): void {
    let rot = Math.PI / 2 * 3;
    let x = cx;
    let y = cy;
    const step = Math.PI / spikes;

    this.ctx.beginPath();
    this.ctx.moveTo(cx, cy - outerRadius);
    
    for (let i = 0; i < spikes; i++) {
      x = cx + Math.cos(rot) * outerRadius;
      y = cy + Math.sin(rot) * outerRadius;
      this.ctx.lineTo(x, y);
      rot += step;

      x = cx + Math.cos(rot) * innerRadius;
      y = cy + Math.sin(rot) * innerRadius;
      this.ctx.lineTo(x, y);
      rot += step;
    }
    
    this.ctx.lineTo(cx, cy - outerRadius);
    this.ctx.closePath();
  }

  public play(): void {
    this.isPlaying = true;
    this.animate();
  }

  public pause(): void {
    this.isPlaying = false;
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
  }

  private animate(): void {
    if (!this.isPlaying) return;
    this.animationFrameId = requestAnimationFrame(() => this.animate());
  }

  public resize(width: number, height: number): void {
    this.canvas.width = width;
    this.canvas.height = height;
  }
}